package com.situ.web.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/insertStudent")
public class InsertStudentServlet extends HttpServlet{

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("InsertStudentServlet.service()");
		//解决post传参乱码问题
		req.setCharacterEncoding("UTF-8");
		// http://localhost:8080/Java1912Web/insertStudent?name=zhangsan&age=23&gender=男
		String name = req.getParameter("name");
		String age = req.getParameter("age");
		String gender = req.getParameter("gender");
		System.out.println(name);
		System.out.println(age);
		System.out.println(gender);
		
		
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "INSERT INTO student(`name`,age,gender) VALUES(?,?,?)";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, name);
			preparedStatement.setInt(2, Integer.parseInt(age));
			preparedStatement.setString(3, gender);
			int count = preparedStatement.executeUpdate();
			if (count == 1) {
				System.out.println("插入成功");
			} else {
				System.out.println("插入失败");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, preparedStatement, null);
		}
		
		// 添加完之后再到查询并展示所有的界面
		resp.sendRedirect(req.getContextPath() + "/findAllStudent");
		
	}
	
}